//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Security.Cryptography.X509Certificates;
using System.Collections;
using System.ServiceModel.Description;

namespace Shp.Security.BrokeredReceiver
{
    /// <summary>
    /// This token manager knows how to handle a SAML token. 
    /// </summary>
    public class StsSecurityTokenManager : ServiceCredentialsSecurityTokenManager
    {
        const string SamlTokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";

        public StsSecurityTokenManager(StsServiceCredentials serviceCredentials)
            : base(serviceCredentials)
        {
        }

        public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(
            SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
        {
            if (tokenRequirement.TokenType == SamlTokenType ||
                tokenRequirement.TokenType == SamlConstants.Namespace)
            {
                List<SecurityToken> tokens = GetAllServiceTokens();

                List<SecurityTokenAuthenticator> securityAuthenticators = new List<SecurityTokenAuthenticator>();
                //securityAuthenticators.Add(new CustomUserNameSecurityTokenAuthenticator(UserNamePasswordValidator.None));
                securityAuthenticators.Add(new X509SecurityTokenAuthenticator(X509CertificateValidator.None));

                outOfBandTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), true);
                return new SamlSecurityTokenAuthenticator(securityAuthenticators);
            }
            else
            {
                return base.CreateSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver);
            }
        }

        private List<SecurityToken> GetAllServiceTokens()
        {
            List<SecurityToken> securityTokens = new List<SecurityToken>();

            // Add the scoped certificates
            foreach (X509SecurityToken token in FederationUtilities.GetScopedTokens(ServiceConfiguration.ScopedCertificates).Values)
            {
                securityTokens.Add(token);
            }

            // Add the service certificate
            X509SecurityToken serviceToken = new X509SecurityToken(this.ServiceCredentials.ServiceCertificate.Certificate);
            securityTokens.Add(serviceToken);

            // Add the issuers certificates
            foreach(X509Certificate2 issuer in this.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates)
            {
                securityTokens.Add(new X509SecurityToken(issuer));
            }

            return securityTokens;
        }
    }
}
